package com.yuyou.fn.educational.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.CriteriaUtils;
import com.yuyou.fn.common.util.Threads;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.Room;
import com.yuyou.fn.educational.mapper.RoomMapper;
import com.yuyou.fn.educational.service.*;
import com.yuyou.fn.educational.vo.RoomPriceVo;
import com.yuyou.fn.educational.vo.RoomQueryVo;
import com.yuyou.fn.educational.vo.RoomSaveOrUpdateVo;
import com.yuyou.fn.platform.entity.AreaTeam;
import com.yuyou.fn.platform.service.IAreaTeamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * Room 表数据服务层接口实现类
 */
@Service
public class RoomServiceImpl extends SuperServiceImpl<RoomMapper, Room, Long> implements IRoomService  {

    @Resource
    private ICampusService campusService;

    @Resource
    private IAreaTeamService areaTeamService ;

    @Resource
    private IRoomPriceService roomPriceService;

    @Resource
    private ICourseClassService courseClassService;

    @Resource
    private IClassLectureService classLectureService;

/*
    @Resource
    private IPersonLeaseMessageService personLeaseMessageService;
*/


    @Override
    public void deleteByCampusId(Long campusId) {

        Example<Room> example = Room.createExample();
        example.selectProperties("roomId");
        example.createCriteria().andEqualTo("campusId", campusId);

        List<Room> roomList = findListByExample(example);

        for (Room room : roomList) {
            deleteRoom(room.getRoomId());
        }

    }

    @Override
    public void deleteRoom(Long roomId) {
        //// TODO: 2017/3/2  check

        deleteById(roomId);

    }

    @Override
    public Page<Room> findRoomByQueryForPage(RoomQueryVo roomQueryVo, int pageNo, int pageSize) {
        Example<Room> example = Room.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria, roomQueryVo);
        return findPageByExample(example, pageNo, pageSize);

    }

    @Override
    @Transactional
    public void saveOrUpdateRoom(RoomSaveOrUpdateVo roomSaveOrUpdateVo) {

        Room room = new Room();
        BeanUtils.copyProperties(room, roomSaveOrUpdateVo);
        checkRoomName(room);
        fillExtraData(room);
        if (room.getRoomId() == null) {
            room.setCreateTime(TimeUtils.now());
            room.setUpdateTime(TimeUtils.now());
            insertSelective(room);
            roomSaveOrUpdateVo.setRoomId(room.getRoomId());
        } else {
            room.setUpdateTime(TimeUtils.now());
            Room check=this.findById(room.getRoomId());
            final Long roomId=check.getRoomId();
            final String roomName=room.getRoomName();
            if (!check.getRoomName().equals(room.getRoomName())){
                Threads.dispatch(new Runnable() {
                    @Override
                    public void run() {
                        courseClassService.updateRoomNameByRoomId(roomId,roomName);
                    }
                });
            }
            updateSelectiveById(room);
        }
        if (roomSaveOrUpdateVo.getSummerWinterDateId()!=null){
            RoomPriceVo roomPriceVo=new RoomPriceVo();
            BeanUtils.copyProperties(roomPriceVo,roomSaveOrUpdateVo);
            roomPriceService.addByRoomPriceVo(roomPriceVo);
        }

    }

    private void fillExtraData(Room room) {
        Campus campus = campusService.findById(room.getCampusId());
        room.setCampusName(campus.getCampusName());
        room.setProvince(campus.getProvince());
        room.setCity(campus.getCity());
        room.setDistrict(campus.getDistrict());
        //room.setBelongTeamIds(campus.getBelongTeamIds());
        room.setAddress(campus.getAddress());
    }

    private void checkRoomName(Room room) {
        Example<Room> example = Room.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("campusId",room.getCampusId()).andEqualTo("roomName" , room.getRoomName());
        Room one = findOneByExample(example);
        if(one != null &&(room.getRoomId() == null || !one.getRoomId().equals(room.getRoomId()))){
            throw new BusException("教室名重复");
        }
    }

    @Override
    public Page<Room> findRoomListForClassArrangement(RoomQueryVo roomQueryVo, Long areaTeamId, int pageNo, int pageSize) {
        roomQueryVo.setStatus(1);
        AreaTeam areaTeam = areaTeamService.findById(areaTeamId);


        Example<Room> example = Room.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria, roomQueryVo);
        if(areaTeam.getCity() != null ){
            List<Campus> campusList = campusService.findCampusByCityFromCache(areaTeam.getCity());
            List<Long> campusIds  = BeanUtils.toList(campusList,"campusId");
            criteria.andIn("campusId",campusIds );
        }
        return findPageByExample(example, pageNo, pageSize);
    }

  /*  @Override
    public List<Room> findRoomByBuyOrCreate(Long classId, SysUser sysUser,Long campusId) {
        CourseClass courseClass=courseClassService.findById(classId);
        Long busTeamId=courseClass.getBusTeamId();
        Long areaTeamId=courseClass.getAreaTeamId();
        List<ClassLecture> classLectureList=classLectureService.findClassLectureByClassId(classId);
        BitSet bitSet=new BitSet();
        Date minDate=null;
        Date maxDate=null;
        for (ClassLecture classLecture:classLectureList){
            String startStr= Utils.formatDate(classLecture.getClassDate(),"yyyy-MM-dd")+" "+classLecture.getStartTime();
            Date startDate=Utils.parseDate(startStr,"yyyy-MM-dd HH:mm:ss");
            String endStr=Utils.formatDate(classLecture.getClassDate(),"yyyy-MM-dd")+" "+classLecture.getEndTime();
            Date endDate=Utils.parseDate(endStr,"yyyy-MM-dd HH:mm:ss");
            bitSet.set(TimeUtils.toMini(startDate),TimeUtils.toMini(endDate));
            if (minDate==null || minDate.getTime()>startDate.getTime()){
                minDate=startDate;
            }
            if (maxDate==null || maxDate.getTime()<endDate.getTime()){
                maxDate=endDate;
            }
        }
        if (sysUser.getUserType()==1 || sysUser.getUserType()==0){
            List<Room> roomList=this.findByAreaTeamIdAndCampusAndStatus(areaTeamId,campusId,1);
            List<Long> roomIdList=BeanUtils.toList(roomList,"roomId");
            if (roomIdList==null || roomIdList.size()<=0){
                return null;
            }
            PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
            personLeaseQueryVo.setRoomIds(roomIdList);
            personLeaseQueryVo.setLeaseState(1);
            personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);

        }









        PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
        personLeaseQueryVo.setPayMainAccountId(busTeamId);
        personLeaseQueryVo.setLeaseState(1);
        List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
        Map<Long,List<PersonLeaseMessage>> roomListMap=BeanUtils.toGroup(personLeaseMessageList,"roomId");
        Iterator<Map.Entry<Long, List<PersonLeaseMessage>>> entries = roomListMap.entrySet().iterator();
        while (entries.hasNext()){
            Map.Entry<Long, List<PersonLeaseMessage>> entry = entries.next();
            List<PersonLeaseMessage> roomLease=entry.getValue();
            BitSet roomSet=new BitSet();
            List<TimeStampLong> timeStampLongList=new ArrayList<TimeStampLong>();
            //personLeaseMessageService.findTimeStampLongByPersonLease()

        }


        return null;
    }
*/
    @Override
    public List<Room> findListByCampusId(Long campusId, Long areaTeamId, Long busTeamId) {
        Example<Room> example = Room.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("campusId",campusId);
        CriteriaUtils.fillCondition(criteria,areaTeamId , busTeamId );
        return findListByExample(example);
    }

    @Override
    public Room findByUserIdAndRoomId(Long userId, Long roomId) {
        Example<Room> example = Room.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        criteria.andEqualTo("roomId",roomId);
        return findOneByExample(example);
    }

    @Override
    public List<Room> findByCond(List<Long> campusIdList, Long campusId, String roomName, Integer status) {
        Example<Room> example = Room.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",status);
        if (campusId!=null){
            criteria.andEqualTo("campusId",campusId);
        }else {
            if (campusIdList==null ||campusIdList.size()<=0){
                return Collections.EMPTY_LIST;
            }
            criteria.andIn("campusId",campusIdList);
        }
        if (StringUtils.isNotEmpty(roomName)){
            criteria.andLike("roomName","%"+roomName+"%");
        }
        return findListByExample(example);
    }

    @Override
    public Page<Room> findByRoomIds(List<Long> roomIds, int pageNo, int pageSize) {
        if (roomIds==null || roomIds.size()<=0){
            Page<Room> page=new Page<>(pageNo,pageSize);
            page.setTotal(0);
            return page;
        }
        Example<Room> example=Room.createExample();
        example.createCriteria().andIn("roomId",roomIds);
        return findPageByExample(example,pageNo,pageSize);
    }

    @Override
    public void updateCampusNameByCampusId(Long campusId, String campusName) {
        if (campusId!=null){
            Example<Room> example=Room.createExample();
            example.createCriteria().andEqualTo("campusId",campusId);
            Room room=new Room();
            room.setCampusName(campusName);
            this.updateSelectiveByExample(room,example);
        }
    }

}